﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SimpleBoard.DependencyInjection;
using System.Windows;
using System;
using SimpleBoard.Designer.Services;
using System.IO;

namespace SimpleBoard.Designer
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private readonly IHost host;

        public App()
        {
            host = Host.CreateDefaultBuilder()
                       .UseAutoInjection()
                       .Build();
        }

        public static new App Current => (App)Application.Current;

        internal static T AutoWired<T>()
        {
            var service = Current.host.Services.GetService<T>();
            if (service is null) throw new NullReferenceException($"服务{nameof(T)}不存在");
            return service;
        }

        private void OnStartup(object sender, StartupEventArgs e)
        {
            App.AutoWired<MainWindow>().Show();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            var controlAssemblyDirectory = new DirectoryInfo("Controls");
            if (!controlAssemblyDirectory.Exists) controlAssemblyDirectory.Create();

            var service = App.AutoWired<ControllerService>();
            foreach (var file in controlAssemblyDirectory.GetFiles())
            {
                if (file.Extension != ".dll") continue;
                service.LoadControllerAssembly(file.FullName);
            }
            base.OnStartup(e);
        }

        protected override async void OnExit(ExitEventArgs e)
        {
            using (host)
            {
                await host.StopAsync();
            }

            base.OnExit(e);
        }
    }
}
